<?php
class Admin_PicturesController extends Zend_Controller_Action
{
    protected $_flashMessenger = null;
    protected $imagesRoot = "upload/image/";

    public function init()
    {
        $this->_flashMessenger = $this->_helper->getHelper('FlashMessenger');
        $this->initView();
    }

	function addAction()
	{
		$form = new PictureForm();
		$this->view->form = $form;

		$pairs = Doctrine::getTable('Article')->fetchPairs('id', 'title');
        $articleSelect = $form->getElement('article_id');
        $articleSelect->addMultioption('0', '---Select article---');
        $articleSelect->addMultioptions($pairs);

        if($this->_request->isPost())
        {
            $formData = $this->_request->getPost();
            if($form->isValid($formData))
            {
                $filtered_data = $form->getValues(true);

                $target_path = $this->imagesRoot . basename( $filtered_data['file']['name']);
                move_uploaded_file($filtered_data['file']['tmp_name'], $target_path);

                $picture = new Picture();
                $picture->merge($filtered_data);
                $picture->filename = $filtered_data['file']['name'];
                $picture->save();

                $this->_flashMessenger->addMessage('Picture uploaded!');
                $this->_helper->redirector('index');;
            }
            else
            {
                $form->populate($formData);
            }
        }// if isPost
	}

    function editAction()
    {
        $form = new PictureForm();
        $form->submit->setLabel('Save');

        $this->view->form = $form;
        $form->getElement('file')
                 ->setRequired(false)
                 ->removeValidator('NotEmpty')
                 ;

        $pairs = Doctrine::getTable('Article')->fetchPairs('id', 'title');
        $articleSelect = $form->getElement('article_id');
        $articleSelect->addMultioption('0', '---Select article---');
        $articleSelect->addMultioptions($pairs);

        $picture = $this->_findRecord();

        if($this->_request->isPost()) {
            $formData = $this->_request->getPost();
            if($form->isValid($formData))
            {
                $filtered_data = $form->getValues(true);
                $picture->merge($filtered_data);

                //if the picture was uploaded successfully
                if(!$filtered_data['file']['error'])
                {
                	//move uploaded image to imagesRoot
	                $target_path = $this->imagesRoot . basename( $filtered_data['file']['name']);
	                move_uploaded_file($filtered_data['file']['tmp_name'], $target_path);

	                //remove previous image and thumbnail
	                $prevImgPath = $this->imagesRoot . basename($picture->filename);
	                unlink($this->_thumb($prevImgPath));
	                unlink($prevImgPath);

	                //link with the new picture
	                $picture->filename = $filtered_data['file']['name'];
                }

                $picture->save();

                $this->_flashMessenger->addMessage('Picture updated!');
                $this->_helper->redirector('index');
            }
            else
            {
                $form->populate($formData);
            }
        }
        else {
            $form->populate($picture->toArray());

            $imagePath = $this->imagesRoot . basename($picture->filename);
            $thumbnail = $this->_thumb($imagePath);

            $picture = new Zend_Form_Element_Image('picture');
            $picture
                ->setLabel('Picture')
                ->setImage($thumbnail)
                ->setOrder(6)
                ;
            $form->addElement($picture);

            $this->view->imagePath = $imagePath;
        }
    }

    function deleteAction()
    {
		$picture = $this->_findRecord();
        
        if($this->_request->isPost())
        {
            $del = $this->_request->getPost('del');
            if ($del == 'Yes')
            {
                //remove image and thumbnail
                $imgPath = $this->imagesRoot . basename($picture->filename);
                unlink($imgPath);
                unlink($this->_thumb($imgPath, false));

                $picture->delete();

                $this->_flashMessenger->addMessage('Picture deleted!');
            }

            $this->_helper->redirector('index');
        }
        else
        {
            $imagePath = $this->imagesRoot . basename($picture->filename);

            $this->view->thumbnail = $this->_thumb($imagePath);
            $this->view->picture = $picture;
        }
    }

	function indexAction()
	{
        $this->view->articleSelect = Doctrine::getTable('Article')->createSelect(false);

        $this->view->flash = $this->_flashMessenger->getMessages();
	}

    function ajaxFetchPicturesAction()
    {
        $params = array(
            'page'    => $this->_request->getParam('page', 1),
            'limit'     => $this->_request->getParam('rows', 20),
            'sort'      => $this->_request->getParam('sidx', 'id'),
            'dir'       => $this->_request->getParam('sord', 'ASC'),
            'article_id'  => $this->_request->getParam('article_id', 0),
        );

        $rawData = Doctrine::getTable('Picture')->fetchExtGridData($params);

        $this->_helper->json($rawData);
    }

    /**
     * Creates thumbnail and returnes path to it
     *
     * @param string $filepath Source file
     * @param boolean $create Specifies whether to create thumbnail or return path only (default true)
     * @param integer $x X dimension
     * @param integer $y Y dimension
     * @return string Path to thumbnail
     */
    protected function _thumb($filepath, $x = 200, $y = 200)
    {
    	$thumb = new ImgResize($filepath);
    	$thumb_name = $thumb->resize($x, $y);

        return $thumb_name;
    }
    
    /**
     * Finds record in database
     * 
     * @return Doctrine_Record
     */
    protected function _findRecord()
    {
        $id = (int) $this->_request->getParam('id');
        $record = Doctrine::getTable('Picture')->find($id);
        if (!$record) throw new Zend_Controller_Dispatcher_Exception();

        return $record;
    }    
    
}
?>